/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import com.sun.lwuit.Command;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Label;
import com.sun.lwuit.TextArea;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.layouts.BoxLayout;
import core.DriverManager;
import core.Settings;
import core.TaxiMIDlet;
import network.Connection;
import network.PacketBuilder;
import view.commands.BackCommand;
import view.commands.CenterCommand;


/**
 *
 * @author Kvest
 */
public class UpdateForm extends Form
{
    private String link; 
    
    public UpdateForm(String link, boolean mustUpdate)
    {
        super("update");
        
        this.link = link;
        
        init(mustUpdate);
    }
    
    private void init(boolean mustUpdate)
    {
        setLayout(new BoxLayout(BoxLayout.Y_AXIS));
        setCyclicFocus(false);
        
        TextArea text = new TextArea((new Label("update_text")).getText(), 1, 30);
        text.setAlignment(TextArea.LEFT);
        text.setEditable(false);
        text.setFocusable(false);
        addComponent(text);

        if (!mustUpdate)
        {
            BackCommand backCommand = new BackCommand();
            backCommand.setCommandName("cancel");
            CenterCommand centerCommand = new CenterCommand(backCommand);
            if (!Display.getInstance().isTouchScreenDevice())
            {
                addCommand(centerCommand);
            }    
            addCommand(backCommand);
        }
        
        Command load = new Command("do_update")
        {
            public void actionPerformed(ActionEvent evt)
            {
                doUpdate();
            }
        };
        if (mustUpdate)
        {
            CenterCommand centerCommand = new CenterCommand(load);
            if (!Display.getInstance().isTouchScreenDevice())
            {
                addCommand(centerCommand); 
            }
        }
        addCommand(load);
    }
    
    private String getLink()
    {
        String result = link + Settings.getSettings().getUpdateType();
        
        if (!result.startsWith("http://"))
        {
            result = "http://" + result;
        }
    
        return result;
    }
    
    private void doUpdate()
    {
        //Отправляем пакет дисконекта
        Connection.getConnection().send(PacketBuilder.createExitRequest(DriverManager.getManager().getDriverID()));

        //Останавливаем соединение
        Connection.getConnection().stop();

        //Начинаем обновление
        try
        {
            TaxiMIDlet.getMidlet().platformRequest(getLink());
        }
        catch(Exception ex){}
        
        //Закрываем приложение
        TaxiMIDlet.getMidlet().destroyApp(true);
    }
}
